package com.jckl.foodathon.services.config;

import java.io.IOException;

import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jckl.foodathon.common.constant.ApplicationConstants;
import com.jckl.foodathon.common.constant.CommunicationConstants;
import com.jckl.foodathon.common.utils.BitmapEncode;
import com.jckl.foodathon.model.Response;
import com.jckl.foodathon.model.Store;

public class NewStoreConfiguration {
	
	public void perform(Activity activity, Store store){

		PerformNewStoreAsync async = new PerformNewStoreAsync(activity, store);
		async.execute();
	}
	
	private class PerformNewStoreAsync extends AsyncTask<Void, Void, Boolean> {
		
		Context context;
		Store store;
		Response response;
		Activity activity;
		
		public PerformNewStoreAsync(Activity activity, Store store){
			this.activity = activity;
			this.context = activity.getApplicationContext();
			this.store = store;
		}
		
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(Void... nothing) {
			
			boolean responseSuccess = false;
			
			try {
				if(store.getImage() != null){
					store.setEncodedImage(BitmapEncode.bitmapToEncodedString(store.getImage()));
					store.setImage(null);
				}
				
				Gson gson = new Gson();
				Log.i(CommunicationConstants.APP_TAG, "Store JSON: "+gson.toJson(store));
				
				ClientResource cr = new ClientResource(CommunicationConstants.SERVER_URI + CommunicationConstants.DATA_STORE);
				JacksonRepresentation<Store> storeJson = new JacksonRepresentation<Store>(store);
				Representation rep = cr.post(storeJson);
			
				String responseStatus = rep.getText();
				response = gson.fromJson(responseStatus, Response.class);
				
				if(response.getServerResponse() == ApplicationConstants.SERVER_RESP_SUCCESS)
					responseSuccess = true;
				
			} catch (IOException IOex) {
				Log.e(CommunicationConstants.APP_TAG, "Unable to parse return value");
				IOex.printStackTrace();
			} catch (Exception ex){
				ex.printStackTrace();
			}
			
			return responseSuccess;
		}
		
		@Override
		protected void onProgressUpdate(Void... nothing){
	    }

		
		@Override
		protected void onPostExecute(Boolean responseSuccess) {
			if(responseSuccess){
				Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
				//Refresh the store info into sqlite
				GetAllStoreInfo storeInfo = new GetAllStoreInfo();
				storeInfo.perform(activity);
			}else{
				Toast.makeText(context, "Error: "+response.getRemark(), Toast.LENGTH_SHORT).show();
			}
	    }
	}

}
